//
//  RequestWork.m
//  WisdomShope
//
//  Created by mac on 15/12/26.
//  Copyright (c) 2015年 ZY. All rights reserved.
//

#import "RequestWork.h"

@implementation RequestWork


#pragma mark AFN get请求（网络请求时的图片动画展示）
+ (void)afGetHttpWihtRUL:(NSString *)urlString wihtParmas:(NSDictionary *)parmas successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{

    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    //申明请求的数据是json类型
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:urlString parameters:parmas progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        fileBlock(error);
    }];

   
    
    
}
#pragma mark AFN post请求（网络请求时的图片动画展示）
+ (void)POSTOfAFNWithURL:(NSString *)url pamars:(NSDictionary *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
 
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:url parameters:pamars progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        fileBlock(error);
    }];
    
    
}
#pragma mark AFN POST请求 form data 格式
+ (void)sendWeiboUseAFNetWoringWithURL:(NSString *)url pamars:(NSDictionary *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *lvl = [pamars objectForKey:@"lvl"];
    UIImage *image = [UIImage imageNamed:@"find_nav_search@2x"];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    NSData *da = [data base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    [manager POST:url parameters:@{@"lvl":lvl} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:da name:@"img" fileName:@"aia.jpg" mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        fileBlock(error);
        
    }];
 
}







+ (NSString *)parmasStringWithParmas:(NSDictionary *)parmas{
    
    NSMutableString *parmasString = [[NSMutableString alloc] init];
    
    for (NSString *key in parmas) {
        
        [parmasString appendFormat:@"%@=%@",key,[parmas objectForKey:key]];
        
        if (key != [[parmas allKeys]lastObject]) {
            
            [parmasString appendFormat:@"&"];
        }
        
    }
    
    return parmasString;
}


/*网络请求的三大步骤
 
 1. 设置请求路径 NSURL
 2. 构造一个请求对象 NSURLrequest ：请求体 请求方法 包含请求路径
 3. 发送请求11
 */

+ (void)httpRequestWithURL:(NSString *)urlString parmas:(NSDictionary *)parmas httpMethod:(NSString *)method successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    
    //1，设置请求路径
    NSURL *rul = [NSURL URLWithString:urlString];
    //拼接传入参数
    NSString *parmasString = [self parmasStringWithParmas:parmas];
    
    //构建网络请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:rul];
    [request setHTTPMethod:method];
    [request setTimeoutInterval:60];

    if ([method isEqualToString:@"GET"]) {
        
        //设置请求查询的字符
        NSString *separe = rul.query?@"&":@"?";
        
        NSString *fullString = [NSString stringWithFormat:@"%@%@%@",rul,separe,parmasString];
        //改称UTF8形式
        NSURL *fullUrl = [NSURL URLWithString:[fullString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [request setURL:fullUrl];
        
    }else{
        
        [request setHTTPBody:[parmasString dataUsingEncoding:NSUTF8StringEncoding]];
    
        
    }
    
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            
            id reqestob = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            successBlock(reqestob);
        }
        
        if (error) {
            
            fileBlock((NSHTTPURLResponse*)response);
        }
        
    }];
    [task resume];
    
}
#pragma mark put
+ (void)sendputwith:(NSString *)url parmas:(NSDictionary *)parmas successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    [manager PUT:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        fileBlock(error);
    }];
    
}

#pragma mark 修改个人信息
+ (void)changeUserImageUseAFNetWoringWithURL:(NSString *)url parmas:(NSDictionary *)parmas imageFileName:(NSString *)filName image:(UIImage *)image successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    

    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:data name:filName fileName:fileName mimeType:@"image/jpeg"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        fileBlock(error);
    }];
    
}
#pragma mark 上传视频POST
+ (void)upMoveWithURL:(NSString *)url pamars:(NSString *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
   
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
//        NSData *data = UIImageJPEGRepresentation(pamars, 0.5);
        NSData *_data = [NSData dataWithContentsOfFile:pamars];
        NSData *data = [[NSData alloc] initWithData:_data];
        
//        获取文件名
        NSString *fileName = [pamars lastPathComponent];
//        获取文件格式
//        NSString *fileType = [pamars pathExtension];
        [formData appendPartWithFileData:data name:@"videoFile" fileName:[NSString stringWithFormat:@"%@.mp4",fileName] mimeType:@"mp4"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        fileBlock(error);
    }];
    
}
#pragma mark 上传多张图片
+ (void)upMoreImageURL:(NSString *)url pamars:(NSDictionary *)normalPamars picture:(UIImage *)pictureimage imgArr:(NSArray *)imgArr successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    
    [manager POST:url parameters:normalPamars constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(pictureimage){
            NSData *dataPicture = UIImageJPEGRepresentation(pictureimage, 0.5);
            [formData appendPartWithFileData:dataPicture name:@"picture" fileName:@"picture.jpg" mimeType:@"image/jpg"];
        }
        
        int i = 0;
        for (UIImage *image in imgArr) {
            i ++;
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg", str,i];
            [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"img%d",i] fileName:fileName mimeType:@"image/jpg"];
            
        }
        
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        fileBlock(error);
    }];
    
}



@end
